package cn.sylinx.horm.config.specific;

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import cn.sylinx.horm.config.OrmConfig;
import cn.sylinx.horm.config.OrmConfigHolder;
import cn.sylinx.horm.util.GLog;

/**
 * 基于不同数据源的配置
 * 
 * @author johnhan
 *
 */
public enum SpecificConfigHolder {

    ;

    private static final Map<String, SpecificConfig> dataSourceConfigMaps = new HashMap<>();

    public static void init(OrmConfig ormConfig, Map<String, SpecificConfig> dataSourceConfig) {
        if (dataSourceConfig != null && !dataSourceConfig.isEmpty()) {
            Set<Entry<String, SpecificConfig>> entrySet = dataSourceConfig.entrySet();
            for (Entry<String, SpecificConfig> entry : entrySet) {
                addSpecificConfig(ormConfig, entry.getKey(), entry.getValue());
            }
        }
    }

    public static void addSpecificConfig(OrmConfig ormConfig, String specificKey, SpecificConfig specificConfig) {
        // 加载配置
        loadSpecific(ormConfig, specificKey, specificConfig);
        dataSourceConfigMaps.put(specificKey, (SpecificConfig) specificConfig.clone());
        GLog.info("addSpecificConfig, specificKey:{}, specificConfig:{}", specificKey, specificConfig);
    }

    private static void loadSpecific(OrmConfig ormConfig, String specificKey, SpecificConfig baseConfig) {
        // Do Nothing
    }

    public static boolean isSqlStatOpen(String dataSourceName) {

        SpecificConfig config = dataSourceConfigMaps.get(dataSourceName);
        if (config == null) {
            return OrmConfigHolder.isSqlStatOpen();
        }
        return OrmConfigHolder.isSqlStatOpen() && config.isSqlStatOpen();
    }

    public static boolean isSqlClientInterceptorEnable(String dataSourceName) {

        SpecificConfig config = dataSourceConfigMaps.get(dataSourceName);
        if (config == null) {
            return true;
        }
        return OrmConfigHolder.getSqlClientInterceptor() != null && config.isSqlClientInterceptorEnable();
    }
}
